<?php
/**
 * 名称：Authorization.php
 * 功能：后台权限验证
 * 作者: Qiyuan<mqycn@126.com>
 * 更新：http://git.oschina.net/mqycn/thinkAuthorization5/
 */

namespace app\common\behavior;

class Authorization {

	/**
	 * 当前控制器
	 */
	private $thisController;

	/**
	 * 选项
	 */
	protected $option = [
		"authorization_open" => false,
		"authorization_url" => "/Login#AuthorizationError",
	];

	/**
	 * 默认权限，如果不设置无法访问设置页面
	 */
	private $authDefault = [
		"admin/index/index",
		"admin/authorization/index",
		"admin/authorization/add",
		"admin/authorization/edit",
		"admin/authorization/save",
		"admin/authorization/update",
	];

	/**
	 * 入口
	 */
	public function run(&$controller) {
		if (config("authorization.authorization_open")) {
			$this->thisController = $controller;
			$arg = $this->check();
		}
	}

	/**
	 * 错误页面，如果 当前控制器存在 存在 _ShowError，调用_ShowError
	 */
	private function error($message) {
		if (!config("authorization.authorization_url")) {
			$bad_url = url($this->option['authorization_url']);
		} else {
			$bad_url = url(config("authorization.authorization_url"));
		}
		if (in_array("_ShowError", get_class_methods($this->thisController))) {
			$this->thisController->_ShowError($message, $bad_url);
		} else {
			die('<!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>' . $message . '</title></head><body style="background:#CCC;"><div style="background:#EEE;width:400px;position:absolute;left:50%;top:20%;margin-left:-200px;border:solid 5px #999;color:#666;padding:20px;border-radius:15px;"><h1>:( 鉴权出错了!</h1><hr /><p><a style="color:#333;text-decoration:none;" href="' . $bad_url . '">' . $message . '，如果没有跳转点击这里</a></p></div><script>setTimeout(function(){location.href = "' . $bad_url . '"}, 300000);</script></body></html>');
		}
	}

	/**
	 * 获取当前运行参数
	 */
	private function getRunStatus() {

		$arr = [];
		$ver = explode(".", THINK_VERSION);

		if ('5' == $ver[0]) {
			$arr['Module'] = request()->module();
			$arr['Controller'] = request()->controller();
			$arr['Action'] = request()->action();
		} else {
			$this->error("权限验证：暂时只支持ThinkPHP5.x");
		}
		$arr['URI'] = strtolower($arr['Module']) . '/' . strtolower($arr['Controller']) . '/' . strtolower($arr['Action']);
		return $arr;
	}

	/**
	 * 读取当前登陆用户组的权限配置
	 */
	private function getAuthList() {
		$gid = session("auth_group");
		if (!cache('auth_group_' . $gid)) {
			$UserGroup = db("AuthGroup");
			$user_group = $UserGroup->find($gid);

			if ($user_group) {
				$auth_array = unserialize($user_group['ag_auth']);
				//不存在权限，则写入默认权限
				if (!is_array($auth_array)) {
					$auth_array = $this->authDefault;
					$data = [
						'ag_auth' => serialize($auth_array),
						'ag_id' => $gid,
					];
					$UserGroup->update($data);
				}
				cache('auth_group_' . $gid, $auth_array);
			} else {
				$this->error("权限验证：用户权限组不存在，请联系管理员处理");
			}
			unset($UserGroup);
		}
		return cache('auth_group_' . $gid);
	}

	/**
	 * 检查是否有权限
	 */
	private function check() {
		$_auth = $this->getAuthList();
		$_run = $this->getRunStatus();
		if (!in_array($_run['URI'], $_auth)) {
			$msg = "权限验证：没有权限";
			if (true === config("app_debug")) {
				$msg .= "(" . $_run['URI'] . ")";
			}
			$this->error($msg);
		}

	}
}
?>